<template>
  <PageWrapper contentFullHeight>
    <template #headerContent>
      <div :style="{display: 'flex', justifyContent: 'space-between', width: '100%'}">
        <header class="title" v-text="title"></header>
      <!-- <Button type="primary" @click="handlePrint">打印</Button> -->
      <section class="btnRight">
        <a-button
          class="btn btnBackground"
          size="large"
          preIcon="ant-design:printer-outlined"
          @click="handlePrint"
          :style="marginRight10"
        >
          打印报表
        </a-button>
        <!-- <PrinterOutlined /> -->
        <a-button @click="downLoadExcel" class="btn btnBackground" size="large">保存报表</a-button>
      </section>
      </div>
    </template>
    <section class="reportManagerWrapper">
      <div class="menuWrapper">
        <header class="menuHeader"> 选择报表类型 </header>
        <Menu v-model:selectedKeys="selectedKeys" style="width: 100%">
          <template v-for="item in menuList" :key="item.id">
            <MenuItem >
              <template #icon >
                <div class="menuIcon">
                  <img
                    v-show="!selectedKeys.includes(item.id)"
                    src="@/assets/icons/reportManagerMenuIcon.png"
                    width="14"
                    height="14"
                  />
                  <img
                    v-show="selectedKeys.includes(item.id)"
                    src="@/assets/icons/reportManagerMenuIconSelect.png"
                    width="14"
                    height="14"
                  />
                </div>
              </template>
              <span class="menuText">{{ item.label }}</span>
            </MenuItem>
          </template>

        </Menu>
      </div>
      <div class="tableWrapper">
        <header class="btnWrapper">
          <section class="btnLeft">
            <!-- 根据不同报表类型 使用不同的顶部搜索 -->
            <!-- 酒店营业数据报表 -->
            <MonthSearch @search-data-btn="searchMonthDataBtn" v-if="selectedKeys.includes('1')" @on-search-change="handleSearchChange" @searchData="searchMonthData" ref="monthSearchRef" />
      
            <!-- 订单明细表 -->  <!-- todo AI_范例：此处定义订单明细表的搜索组件，组件内容 OrderDetailReportFormsSearch.html -->
            <OrderDetailReportFormsSearch @searchDataBtn="handleSearchBtn" @onSearchChange="handleOrderDetailDateChange" @searchData="handleOrderDetailInit" v-if="selectedKeys.includes('8')"></OrderDetailReportFormsSearch>

            <!-- AR帐报表 -->  <!-- todo AI_生成：此处生成AR帐报表的搜索组件，参考订单明细表搜索组件创建组件文件 -->

          </section>
        </header>
        <main class="mainContainer">
          <section v-if="isShowSelectBox()" class="fieldListWrapper">
            <span class="fieldText">字段列表：</span>
            <div class="fieldItemWrapper">
              <section
                v-for="(item, index) in fieldList"
                :style="marginRight10"
                :key="item.label + index"
              >
                <Checkbox v-model:checked="item.isSelect" @change="onFieldChange(item)">
                  {{ item.label }}
                </Checkbox>
              </section>
            </div>
            <div class="flex justify-between">
              <Button class="btn" @click="onSaveCheckBoxSelectStatus" type="primary">保存</Button>
              <Button class="btn ml-10px" @click="resetChckboxSelectStatusFn">重置</Button>
            </div>
          </section>
          <PrintTable
            v-if="selectedKeys.includes('1')"
            ref="printRef"
            :exportTime="exportTime"
            :printYearMonthValue="printYearMonthValue"
            :fieldList="fieldList"
            :tableData="showTableData"
            :houtelName="currentHoutelName"
          />
          
          <!-- 订单明细表 -->  <!-- todo AI_范例：此处定义订单明细表的table表格组件，并传入对应的props参数；组件内容 OrderDetailTable.html -->
          <OrderDetailTable ref="printRef" :houtelName="currentHoutelName" :tableData="showTableData" :fieldList="fieldList" :print-year-month-value="printYearMonthValue" :export-time="exportTime" v-if="selectedKeys.includes('8')"></OrderDetailTable>

          <!-- AR帐报表 -->  <!-- todo AI_生成：此处定义AR帐报表的table表格组件，并传入对应的props参数；参考订单明细表表格组件创建组件文件 -->

        </main>
      </div>
    </section>
    <Loading :loading="compState" :absolute="true" tip="加载中·····"></Loading>
  </PageWrapper>
</template>
<script lang="ts">
  import { ref, reactive, toRefs, onMounted, watch } from 'vue';
  import { clientInfoFieldList, hotelIncomeTransFormFn, isPlainObject, receiptExpendIncomeFields, receiptExpendIncomeDetailFields, receiptPaymentCollectDataFn, checkinREportExcelDataTransformFn, enumDocumentsType, enumChargeToTheRoomFn, enumWeekFn } from './index'
  import Loading from '@/components/Loading/src/Loading.vue'
  import { Menu, MenuItem, Checkbox } from 'ant-design-vue';
  import moment from 'moment';
  import Print from '@/utils/print.js';
  import { PageWrapper } from '@/components/Page';
  import MonthSearch from './components/monthSearch.vue';
  import PaymentSearch from './components/paymentSearch.vue';
  import PrintTable from './components/printTable.vue';
  // todo AI_范例：此处添加订单组件对应的接口
  // todo AI_生成：此处额外添加AR帐组件对应的接口
  import { getCheckOutDayDataApi, getReceiptExpendIncomeReportFormsApi, getHoutelRemissionDetailDataApi, getReceiptPaymentDetailReportFormsApi, getHoutelStockReportFormsApi, getReportFormHeaderApi, getReportFormDataApi, putCheckBoxFieldsSelectApi, putResetCheckboxSelectStatusApi, getPartnersAccountDataApi, getPrePayReportFormByChannelApi, getHoutelHousePriceReportFormsApi, getOrderDetailReportFormsApi, getReceiptPaymentCollectReportFormsApi, getCooperativeMessageDataApi, getReceiptExpendIncomeDetailApi } from '/@/api/sys/reportForms';
  import { Button } from 'ant-design-vue'
  import OrderDetailReportFormsSearch from './components/OrderDetailReportFormsSearch.vue'
  import OrderDetailTable from './components/OrderDetailTable.vue'
  import ReceiptExpendIncomeSearch from './components/ReceiptExpendIncomeSearch.vue'
  import { getHotelDetailByIdApi } from '/@/api/sys/hotel';
  import { useUserStore } from '/@/store/modules/user';
  import { transformExcelDataFn, exportDataToExcel, exportExcelStyleOptions, getCurrentReportFormsNameFn } from './index'
  import { jsonToMultipleSheetXlsx } from '/@/components/Excel/src/Export2Excel';
  import { hasButtonPermission } from '/@/utils';
  import { getCustomListApi } from '/@/api/sys/business/custom';
  export default {
    components: {
      PageWrapper,
      Menu,
      MenuItem,
      Checkbox,
      MonthSearch,
      PaymentSearch,
      PrintTable,
      Loading,
      Button,
      OrderDetailReportFormsSearch,
      OrderDetailTable,
      ReceiptExpendIncomeSearch,
      // todo AI_范例：此处添加AR帐报表的table表格和搜索组件
    },
    setup() {
      const compState = ref(false);

      const monthSearchRef = <any>ref(null);
      const printRef = <any>ref(null);
      const state = reactive({
        title: '报表管理',
        marginRight10: {
          marginRight: '10px',
        },
        marginLeft5: {
          marginLeft: '5px',
        },
        selectedKeys: ['1'],
        // todo AI_范例：此处添加订单组件对应的接口
        // todo AI_生成：此处添加AR帐报表，id为11, show固定使用True
        menuList: <any>[
          { label: '酒店营业数据报表', id: '1' ,show: hasButtonPermission('system:reportManager:monthSearch')},
          { label: '订单明细表', id: '8',show: hasButtonPermission('system:reportManager:OrderDetail')},
        ],
        printYearMonthValue: <any>'',
        fieldList: <any>[],
        exportTime: <any>'',
        originTableData: <any>[],
        showTableData: <any>[],
        currentHoutelName: '',
        currentTableName: ''
      });

      // 需要自定义表头的侧边
      const haveHearderReportFormsArr = ['1', '2', '3', '7', '9', '8', '6'] // todo AI_生成：此处添加需要自定义表头的AR帐报表id为11

      // 监听左侧meun变化
      watch(() => state.selectedKeys[0], () => {
        state.fieldList = []
        state.originTableData = []
        onShowDataChange()
        haveHearderReportFormsArr.includes(state.selectedKeys[0]) && pullReportFormsDataHeader()
        state.selectedKeys[0] === '1' && houtelBusinessDataReport(moment().format('YYYY-MM'))
        state.selectedKeys[0] === '14' && changeTableNameFn(state.selectedKeys[0])
        state.selectedKeys[0] === '13' && changeTableNameFn(state.selectedKeys[0])
      })
      // 监听左侧meun变化
      const receiptExpend = ref<InstanceType<typeof ReceiptExpendIncomeSearch>>()
      const changeTableNameFn = (id: string) => {
        const current = state.menuList.find(item => item.id === id)
        if(current) state.currentTableName = current.label
        setTimeout(() => {
          receiptExpend.value?.searchDataBtn(id) // 酒店营业消费收入
        })
      }

      const resetChckboxSelectStatusFn = async () => {
        openLoading(false)
        try {
          await putResetCheckboxSelectStatusApi(state.selectedKeys[0])
          await pullReportFormsDataHeader()
          onShowDataChange()
        } catch (error) {
        } finally {
          compState.value = false
        }
      }

      const onSaveCheckBoxSelectStatus = async () => {
        const newPayLoadArray = state.fieldList.map(item => {
          return {
            display: item.display,
            fieldId: item.id,
          }
        })
        openLoading(false)
        try {
          await putCheckBoxFieldsSelectApi(newPayLoadArray)
        } catch (error) {} finally {
          compState.value = false
        }
      }

      const handleSearchChange = (e) => {
        state.printYearMonthValue = moment(e).format('YYYY-MM');
        houtelBusinessDataReport(e)
      }

      const pullReportFormsDataHeader = async () => {
        const result = await getReportFormHeaderApi(state.selectedKeys[0])
        state.fieldList = result.data.map(item => {
          return {
            ...item,
            isSelect: item.display === 1
          }
        })
      }
      // 酒店营业数据报表fn
      const houtelBusinessDataReport = async (time?: string) => {
        openLoading(false)
        try {
          const result = await getReportFormDataApi(time ?? state.printYearMonthValue)
          const template = result.data.businessData.dataItems
          template && template.length && template.push({...result.data.businessData, date: '合计'})  // 真实营业日数据的合计total
          // 预测数据
          const preData = result.data.predictiveData?.dataItems
          preData && preData.length && template.push({date: '预测'})
          template.push(...result.data.predictiveData.dataItems)
          preData && preData.length && template.push({...result.data.predictiveData, date: '合计'})
          state.originTableData = template
          onShowDataChange()
        } catch (error) {
        } finally {
          compState.value = false
        }
      }
      const store = useUserStore()
      onMounted(() => {
        setDefaultSelectedKey()
        getHotelDetailByIdApi({hotelId: store.ParamSystem?.hotelId}).then(res => {
          state.currentHoutelName = res.data?.name
        })
        // monthSearchRef.value && monthSearchRef.value.init();
        init();
        isShowSelectBox() && pullReportFormsDataHeader()
      });

      function openLoading(absolute?: boolean) {
        compState.value = true;
      }

      function init() {
        resetExportTime();
        onShowDataChange();
        state.selectedKeys.includes('1') && houtelBusinessDataReport(state.printYearMonthValue)
        state.menuList = state.menuList.filter(item => item.show)
      }

      function resetExportTime() {
        state.exportTime = moment().format('YYYY-MM-DD HH:mm:ss');
      }

      function searchMonthData(searchValue: any) {
        console.log('searchValue', searchValue);
        state.printYearMonthValue = moment(searchValue).format('YYYY-MM');
      }

      const searchMonthDataBtn = (searchValue: any) => {
        state.printYearMonthValue = moment(searchValue).format('YYYY-MM');
        houtelBusinessDataReport(state.printYearMonthValue)
      }

      function searchPaymentData(searchValue: any) {
        console.log('searchValue', searchValue);
        state.printYearMonthValue = 'aaaa'
      }

      function onFieldChange(fieldItem: any) {
        console.log('fieldItem', fieldItem);
        state.fieldList = state.fieldList.map(item => {
          return {
            ...item,
            display: item.isSelect ? 1 : 2,
            fieldId: item.id
          }
        })
        onShowDataChange();
      }

      function handlePrint() {
        resetExportTime()
        setTimeout(() => {
          new Print(printRef.value);
        }, 0)
      }

      const cooperativeReceiveaccountName = ref('')

          // 自动设置默认选中项的函数
    const setDefaultSelectedKey = () => {
      // 获取有权限的菜单项
      const visibleMenuItems = state.menuList.filter(item => item.show !== false);
      // 如果默认选中的项不可见，选择第一个有权限的项
      if (!visibleMenuItems.some(item => item.id === state.selectedKeys[0])) {
        state.selectedKeys = [visibleMenuItems[0]?.id || ''];
      }
    };
      const channelName = ref('')


      // 左侧显示筛选框
      const isShowSelectBox = () => haveHearderReportFormsArr.includes(state.selectedKeys[0])

      // todo AI_范例：此处定义订单明细表初始表格数据接口
      const handleOrderDetailInit = (e, params?: { orderStatus?: string; xiaoshou?: string }) => {
        if(!Array.isArray(e)) return
        const { orderStatus: status, xiaoshou: salesperson } = params || {}
        openLoading()
        state.printYearMonthValue = e?.join('~')
        getOrderDetailReportFormsApi({
          startTime: e[0],
          endTime: e[1],
          status,
          salesperson,
        }).then(result => {
          const tem: any[] = Array.isArray(result.data.items) ? result.data.items : []
          const transFormDataMap = tem.map(item => {
            return {
              ...item,
              hasCreditAccount: enumChargeToTheRoomFn(item.hasCreditAccount)
            }
          })
          tem && tem.length && tem.push({orderNumber: '合计', income: result.data.incomeTotal})
          state.originTableData = transFormDataMap
          onShowDataChange()
        }).finally(() => {
          compState.value = false
        })
      }

      // todo AI_生成：此处定义AR帐报表初始表格数据接口


      const handleOrderDetailDateChange = (e, params) => handleOrderDetailInit(e, params)

      const handleSearchBtn = (e, params) => handleOrderDetailInit(e, params)

      const downLoadExcel = () => {
        const reportFormsName = getCurrentReportFormsNameFn(state.menuList, state.selectedKeys[0]) // 报表名字
        // 库存表二级表头
        if(state.selectedKeys.includes('5')) {
          const bottomHeader = state.fieldList[1].map(item => item.label)
          const fields = state.fieldList[1].map(item => item.name)
          const tem = state.fieldList[0].map(item => item.label)
          let topHeader: any = []
          tem.forEach((item, index) => index === 0 ? topHeader.push(item) : topHeader.push(item, '', ''))
          const concatArr = [topHeader, bottomHeader]
          let current = -2
          const merges = state.fieldList[0].map((item, index) => {
            if(index === 0) return {row: 0, col: 0, rowspan: 2, colspan: 1,}
            return {row: 0, col: current += 3, rowspan: 1, colspan: 3,}
          })
          const config: any = {
            data: state.showTableData,
            headers: concatArr,
            sheetName: "个人信息",
            fields,
            merges,
            attrs: [],
          };
          config.attrs.push(exportExcelStyleOptions(config));
          return exportDataToExcel(config, `${reportFormsName}${state.printYearMonthValue}.xlsx`)
        }
        // 结账日报表二级表头
        if(state.selectedKeys.includes('12')) {
          let topHeader: any = []
          const bottomHeader = state.fieldList[1].map(item => item.label)
          state.fieldList[0].forEach(item => {
            topHeader.push(item.label)
            for(let i = 1; i < item.colSpan; i++) {
              topHeader.push('')
            }
          })
          const fields = state.fieldList[1].map(item => item.name)
          const concatArr = [topHeader, bottomHeader]
          const firstArr = state.fieldList[0]
          const spaceCount = firstArr.map(item => item.colSpan)
          const config: any = {
            data: checkinREportExcelDataTransformFn(state.showTableData, state.fieldList[1]),
            headers: concatArr,
            sheetName: "个人信息",
            fields,
            merges: [
              {row: 0, col: 0, rowspan: 1, colspan: spaceCount[0]},
              {row: 0, col: spaceCount[0], rowspan: 1, colspan: spaceCount[1]},
              {row: 0, col: spaceCount[0] + spaceCount[1], rowspan: 1, colspan: spaceCount[2]}
            ],
            attrs: [],
          };
          config.attrs.push(exportExcelStyleOptions(config));
          return exportDataToExcel(config, `${reportFormsName}${state.printYearMonthValue}.xlsx`)
        }
        // 一级表头
        const template = {}
        let showFieldList = state.fieldList.filter((item: any) => item.isSelect);
        showFieldList.forEach(item => {
          template[item.name] = item.label
        })
        const newExcelTable = isShowSelectBox() ? transformExcelDataFn(state.showTableData, state.fieldList) : transformExcelDataFn(state.showTableData)
        jsonToMultipleSheetXlsx({
          sheetList: [{data: newExcelTable, header: template,},],
          filename: `${reportFormsName}${state.printYearMonthValue}.xlsx`,
        })
      }

      function onShowDataChange(flag?) {
        // 只留下勾选的数据，并把数据按照fieldList的顺序排列
        let showFieldList
        if(flag) {
          showFieldList = state.fieldList[1].filter((item: any) => item.isSelect);
        } else {
          showFieldList = state.fieldList.filter((item: any) => item.isSelect);
        }
        state.showTableData = state.originTableData.map((item: any) => {
          const newItem = {};
          showFieldList.forEach((fieldItem: any) => {
            newItem[fieldItem.name] = item[fieldItem.name];
          });
          return newItem;
        });
      }

      return {
        cooperativeReceiveaccountName,
        monthSearchRef,
        printRef,
        ...toRefs(state),
        searchMonthData,
        searchPaymentData,
        onFieldChange,
        handlePrint,
        compState,
        openLoading,
        handleSearchChange,
        onSaveCheckBoxSelectStatus,
        resetChckboxSelectStatusFn,
        searchMonthDataBtn,
        channelName,
        isShowSelectBox,
        handleOrderDetailDateChange,
        handleSearchBtn,
        receiptExpend,
        downLoadExcel,
        // todo AI_范例：此处导出订单数据的初始化函数
        handleOrderDetailInit,
        // todo AI_生成：此处要额外导出AR帐数据的初始化函数

      };
    },
  };
</script>
<style lang="scss" scoped>
  :deep .ant-page-header {
    background: $background-primary !important;
    margin-top: 4px !important;
    .ant-page-header-heading-title {
      color: #2563eb;
    }
  }
  :deep .ant-menu-vertical {
    border: none;
  }
  :deep .ant-menu .ant-menu-item-selected::before {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    display: block;
    width: 4px;
    content: '';
    background-color: rgb(0, 129, 255);
  }

  :deep .ant-divider-horizontal {
    margin-top: 0;
    margin-bottom: 10px;
  }
  .title {
    color: #2563eb;
    font-weight: 600;
    font-size: 30px;
  }
  .reportManagerWrapper {
    display: flex;
    height: 78vh;
    background: #fff;
    border-radius: 12px;
  }
  .menuWrapper {
    width: 20vw;
    border-right: 1px solid rgb(219, 231, 238);
    overflow: auto;
  }
  .menuHeader {
    padding: 20px 0 20px 40px;
    color: rgb(109, 114, 120);
    font-size: 14px;
    font-weight: bold;
    border-bottom: 1px solid rgb(219, 231, 238);
  }
  .menuIcon {
    display: inline-flex;
    align-content: center;
  }
  .menuText {
    font-size: 14px;
    color: #000;
  }
  .tableWrapper {
    width: 100%;
    padding: 25px 40px 0 25px;
    .btnRight {
      display: flex;
      justify-content: end;
      margin-bottom: 20px;
    }
  }
  .btnWrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .btnLeft {
    display: flex;
  }

  .btn {
    border-radius: 12px;
  }
  .btnBackground {
    font-size: 14px;
    color: #fff;
    background: #424867;
  }
  .mainContainer {
    max-height: 70vh;
    // overflow: auto;
  }
  .fieldListWrapper {
    display: flex;
    align-items: baseline;
    margin: 20px 0;
    padding: 12px 5px;
    border: 1px solid rgb(219, 231, 238);
    border-radius: 12px;
  }
  .fieldText {
    min-width: 70px;
  }
  .fieldItemWrapper {
    display: flex;
    flex-wrap: wrap;
  }
  .btn {
    border-radius: 12px;
  }
</style>
